package logic

import (
	"context"
	"nove/models/mysql"

	"nove/noverpc/internal/svc"
	"nove/noverpc/noverpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectAddLogic) CollectAdd(in *noverpc.CollectAddRequest) (*noverpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line
	tx := mysql.DB.Debug().Begin()
	var collect mysql.Collect
	err := tx.Where("user_id=?", in.UserId).Where("book_id=?", in.BookId).Find(&collect).Error
	if err != nil {
		tx.Rollback()
	}
	if collect.ID == 0 {
		collect = mysql.Collect{
			UserId: int(in.UserId),
			BookId: int(in.BookId),
		}
		err = tx.Create(&collect).Error
		if err != nil {
			tx.Rollback()
		}
	} else {
		err = tx.Delete(&collect).Error
		if err != nil {
			tx.Rollback()
		}
	}
	tx.Commit()
	return &noverpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
